<?php
// +----------------------------------------------------------------------
//  | Company Name  京港网络传媒
// +----------------------------------------------------------------------
//  | Copyright (c) 2018 All rights reserved.
// +----------------------------------------------------------------------
//  | Author: sunburst
// +----------------------------------------------------------------------

namespace services\api;

use Yii;
use common\models\base\BcBodyParts;
use common\models\patient\OperateLog;
use common\models\base\BodyParts;
use common\models\clinic\Clinic;
use common\models\member\Attr;
use common\models\member\Member;
use common\models\rbac\Menu;
use common\models\rbac\RolePermission;
use common\models\rbac\UserRole;
use common\models\patient\User;
use common\models\clinic\Project;
use common\models\clinic\Treatment;
use common\models\clinic\TreatmentDetail;
use common\models\clinic\UserTreatmentProject;
use common\models\clinic\TreatmentRoom;
use common\models\clinic\ProjectBind;
use common\components\Service;
use yii\base\ErrorException;
use yii\web\UploadedFile;
use common\helpers\CommonHelper;

/*
 * 治疗室
 * */

class TreatmentRoomService extends Service
{
    /**
     * 获取治疗室列表
     * @param int $adminId 管理员id
     * @return array
     */
    public static function getTreatmentRoomList($adminId, $projectId)
    {
        $list = TreatmentRoom::find()
            ->where(['project_id' => $projectId, 'status' => TreatmentRoom::STATUS_ENABLE])
            ->select('id, name, icon_id')
            ->orderBy('id desc')
            ->asArray()
            ->all();
        foreach ($list as $key => $value) {
            $list[$key]['clinicProjectList'] = ProjectBind::find()
                ->alias('a')
                ->leftJoin(Project::tableName() . ' b', 'b.id = a.clinic_project_id')
                ->where(['a.treatment_room_id' => $value['id'], 'b.status' => Project::STATUS_ENABLE])
                ->select('b.id, b.name, b.template')
                ->asArray()
                ->all();
            if ($list[$key]['clinicProjectList']) {
                foreach ($list[$key]['clinicProjectList'] as &$c) {
                    $c['num'] = self::countHaveTreatUser($value['id'], $c['id']);
                    if ($c['template'] == Project::TEMPLATE_308 || $c['template'] == Project::TEMPLATE_NAJIN) {
                        $c['unit'] = 'mj';
                    } elseif ($c['template'] == Project::TEMPLATE_311) {
                        $c['unit'] = 'ms';
                    } elseif ($c['template'] == Project::TEMPLATE_HALF_311) {
                        $c['unit'] = 'ms';
                    }  else {
                        $c['unit'] = '';
                    }
                }
            } else {
                unset($list[$key]);
            }
        }
        return $list;
    }

    /**
     * 治疗室治疗项目已治疗人数
     *
     * @param $treatmentRoomId
     * @param $clinicProjectId
     * @return int|string
     */
    public static function countHaveTreatUser($treatmentRoomId, $clinicProjectId)
    {
        $startTime = strtotime(date('Y-m-d', time()));
        $endTime = $startTime + 86399;
        $countHaveTreatUser = Treatment::find()
            ->where(['between', 'created_at', $startTime, $endTime])
            ->andWhere(['treatment_room_id' => $treatmentRoomId, 'clinic_project_id' => $clinicProjectId])
            ->count();

        return $countHaveTreatUser;
    }

    /**
     * 一个治疗室治疗项目列表
     *
     * @param $treatmentRoomId 治疗室ID
     * @param $projectId
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getTreatmentRoomProject($treatmentRoomId, $projectId)
    {
        $treatmentRoom = ProjectBind::find()
            ->alias('a')
            ->innerJoin(Project::tableName() . ' b', 'b.id = a.clinic_project_id')
            ->where(['a.treatment_room_id' => $treatmentRoomId, 'b.status' => Project::STATUS_ENABLE, 'b.project_id' => $projectId])
            ->select('b.id, b.name, b.template')
            ->asArray()
            ->all();
        return $treatmentRoom;
    }

    /**
     * 搜索用户列表
     *
     * @param $keyword 关键词
     * @param $clinicProjectId 治疗项目ID
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function searchPatientByKeyword($keyword, $clinicProjectId, $projectId)
    {
        $userInfo = User::find()
            ->where(['project_id' => $projectId])
            // ->andWhere(['or',['like', 'patient_card_id', $keyword], ['like', 'name', $keyword], ['like', 'mobile', $keyword]])
            ->andWhere(['or',['patient_card_id' => $keyword], ['name' => $keyword], ['mobile' => $keyword]])
            ->select('id, patient_card_id, name, mobile, age, gender')
            ->asArray()
            ->all();

        // 治疗项目信息
        $clinicProjectIs = Project::findOne($clinicProjectId);

        $data = [];
        if ($userInfo) {
            foreach ($userInfo as $key => &$val) {

                // 判断是否在by_clinic_user_treatment_project，不存在则不返回
                $haveTreatNum = UserTreatmentProject::findOne(['patient_card_id' => $val['patient_card_id'], 'clinic_project_id' => $clinicProjectId]);
                if (!$haveTreatNum) {
                    // unset($userInfo[$key]);
                    continue;
                }

                $lastTreat = Treatment::find()
                    ->alias('b')
                    ->select('a.num, a.dose, b.clinic_time, b.gender, b.total_num')
                    ->leftJoin(TreatmentDetail::tableName() . ' a', 'b.id = a.clinic_treatment_id')
                    ->where(['b.clinic_project_id' => $clinicProjectId, 'b.patient_card_id' => $val['patient_card_id']])
                    ->orderBy('b.id desc')
                    ->asArray()
                    ->one();

                $val['clinic_time'] = $lastTreat['clinic_time'] ? date('Y-m-d', $lastTreat['clinic_time']) : '';
                $val['total_num'] = $haveTreatNum->total_num - $haveTreatNum->have_treat_num;
                $val['gender'] = User::$genders[$val['gender']];

                // 311需要多返回剂量
                if ($clinicProjectIs && $clinicProjectIs->template == Project::TEMPLATE_311) {
                    $treatDetail = TreatmentDetail::findOne(['clinic_treatment_id' => $val['id']]);
                    $val['dose'] = $treatDetail ? $treatDetail->dose : '';
                }
                $data[] = $val;
            }
        }
        return $data;
    }

    /**
     * @Notes: 患者最后一次治疗信息
     *
     * @Interface getPatientLastTreat
     * @param $patientId 患者ID
     * @param $clinicProjectId 治疗项目ID
     * @return array|\yii\db\ActiveRecord|null
     */
    public static function getPatientLastTreat($patientId, $clinicProjectId)
    {
        $patientUser = User::find()
            ->andWhere(['id' => $patientId])
            ->select('id, patient_card_id, name, mobile, age, gender')
            ->asArray()
            ->one();
        $lastTreat = UserTreatmentProject::find()
            ->where([
                'clinic_project_id' => $clinicProjectId, 'patient_card_id' => $patientUser['patient_card_id']
            ])
            ->asArray()
            ->one();

        $patientUser['clinic_time'] = $lastTreat['clinic_end_time'] ? date('Y-m-d', $lastTreat['clinic_end_time']) : '';
        $patientUser['total_num'] = $lastTreat['total_num'] ? ($lastTreat['total_num'] - $lastTreat['have_treat_num']) : 0;
        $patientUser['clinic_num'] = $lastTreat['clinic_total_num'] ? $lastTreat['clinic_total_num'] : 0;
        $patientUser['gender'] = User::$genders[$patientUser['gender']];

        // 治疗项目信息
        $clinicProjectIs = Project::findOne($clinicProjectId);

        if ($clinicProjectIs && ($clinicProjectIs->template == Project::TEMPLATE_308 || $clinicProjectIs->template == Project::TEMPLATE_NAJIN)) {

            $lastTreatmentId = Treatment::find()
                ->select('id')
                ->where([
                    'clinic_project_id' => $clinicProjectId,
                    'patient_card_id' => $patientUser['patient_card_id'],
                ])
                ->orderBy('id desc')
                ->asArray()->one();

            $patientUser['list'] = TreatmentDetail::find()
                ->alias('a')
                ->select('
                    a.id, a.project_id, a.patient_card_id, a.clinic_treatment_id,
                    a.body_parts_large_id, a.body_parts_large_name, a.body_parts_small_id,
                    a.body_parts_small_name, a.num, a.dose, b.clinic_time
                    ')
                ->leftJoin(Treatment::tableName() . ' b', 'b.id = a.clinic_treatment_id')
                ->where(['b.id' => $lastTreatmentId['id']])
                ->asArray()
                ->all();
            foreach ($patientUser['list'] as &$val) {
                $val['clinic_time'] = $val['clinic_time'] ? date('Y-m-d H:i', $val['clinic_time']) : '';
            }
        }

        return $patientUser;
    }

    /**
     * 已治疗列表
     *
     * @param $clinicProjectId 治疗项目ID
     * @param $projectId
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function haveTreatPatientList($clinicProjectId, $projectId, $treatmentRoomId)
    {
        $startTime = strtotime(date('Y-m-d', time()));
        $endTime = $startTime + 86399;
        $userTreatInfo = Treatment::find()
            ->select('
                id, patient_card_id, name, mobile, age, 
                gender, clinic_time, clinic_num, total_num,
                patient_signature, remark
             ')
            ->where(['between', 'created_at', $startTime, $endTime])
            ->andWhere(['clinic_project_id' => $clinicProjectId, 'project_id' => $projectId, 'treatment_room_id' => $treatmentRoomId])
            ->orderBy('id desc')
            ->asArray()
            ->all();

        // 治疗项目信息
        $clinicProjectIs = Project::findOne($clinicProjectId);

        foreach ($userTreatInfo as &$val) {

            // 311需要多返回剂量
            if ($clinicProjectIs && $clinicProjectIs->template == Project::TEMPLATE_311) {
                $treatDetail = TreatmentDetail::findOne(['clinic_treatment_id' => $val['id']]);
                $val['dose'] = $treatDetail ? $treatDetail->dose : '';
            }
            // 半舱311需要多返回剂量、大部位
            if ($clinicProjectIs && $clinicProjectIs->template == Project::TEMPLATE_HALF_311) {
                $treatDetail = TreatmentDetail::findOne(['clinic_treatment_id' => $val['id']]);
                $val['dose'] = $treatDetail ? $treatDetail->dose : '';
                $val['body_parts_large_name'] = $treatDetail ? $treatDetail->body_parts_large_name : '';
            }

            $val['clinic_time'] = $val['clinic_time'] ? date('Y-m-d H:i', $val['clinic_time']) : '';
            $userIs = User::findOne(['patient_card_id' => $val['patient_card_id']]);
            $val['patient_user_id'] = $userIs ? $userIs->id : 0;
            $val['gender'] = User::$genders[$val['gender']];
        }
        // 已治疗人数
        $num = count($userTreatInfo);
        return ['list' => $userTreatInfo, 'num' => $num];
    }

    /**
     * 已治疗治疗详情
     *
     * @param $clinicTreatmentId 用户治疗信息ID
     * @return array|\yii\db\ActiveRecord|null
     */
    public static function haveTreatPatientDetail($clinicTreatmentId)
    {
        $userTreatDetail = Treatment::find()
            ->where(['id' => $clinicTreatmentId])
            ->select('id, patient_card_id, name, mobile, age, gender, clinic_time, clinic_num, total_num, patient_signature, remark')
            ->asArray()
            ->one();
        $userTreatDetail['clinic_time'] = $userTreatDetail['clinic_time'] ? date('Y-m-d H:i', $userTreatDetail['clinic_time']) : '';
        $userTreatDetail['gender'] = User::$genders[$userTreatDetail['gender']];
        $userTreatDetail['list'] = TreatmentDetail::find()
            ->where(['clinic_treatment_id' => $clinicTreatmentId])
            ->select('body_parts_large_name, body_parts_small_name, num, dose')
            ->asArray()
            ->all();
        return $userTreatDetail;
    }

    /**
     * 开始治疗
     *
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function startTreat($params)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            // 患者信息
            $patientUser = User::findOne($params['patient_user_id']);

            // 一天中只保留最后一次治疗项目为1
            $updateStatus = self::updateTreatmentStatus($patientUser);

            if (!$updateStatus) {
                return ['code' => 422, 'message' => '治疗失败1'];
            }
            if ($params['template'] == Project::TEMPLATE_HALF_311) {
                $params['num'] = $params['clinic_num'] = 1;
            }

            // clinic_treatment数据添加
            $lastTreat = self::createClinicTreatment($params, $patientUser);
            if (!$lastTreat) {
                return ['code' => 422, 'message' => '治疗失败2'];
            }

            // 模板1（308）【新增纳金模版，同308】
            if ($params['template'] == Project::TEMPLATE_308 || $params['template'] == Project::TEMPLATE_NAJIN) {
                $createTreat = self::createTreatFirstDetail($params, $lastTreat);

            } elseif ($params['template'] == Project::TEMPLATE_311) {
                // 模版2（311）
                $createTreat = self::createTreatOtherDetail($params, $lastTreat, $patientUser);

            } elseif ($params['template'] == Project::TEMPLATE_HALF_311) {
                $createTreat = self::createTreatOtherDetail($params, $lastTreat, $patientUser);
            } else {
                // 其他模版
                $params['num'] = $params['clinic_num'];
                $params['dose'] = 0;
                $createTreat = self::createTreatOtherDetail($params, $lastTreat, $patientUser);
            }

            if (!$createTreat) {
                return ['code' => 422, 'message' => '治疗失败3'];
            }

            // 更新患者表上次治疗时间和上次到院时间
            User::updateAll(['last_clinic_time' => time(), 'last_revisiting_time' => time()], ['id' => $params['patient_user_id']]);

            // 治疗信息操作日志
            self::createOperateLog($params, $patientUser);

            // 更新患者最后一次治疗项目信息
           self::updateUserTreatmentProject($params, $patientUser);

          $transaction->commit();
            return ['code' => 200, 'message' => '治疗成功'];
           } catch (\Exception $exception) {
             $transaction->rollBack();
             throw new \Exception($exception->getMessage(), 500);
         }
    }

    /**
     * 更新用户治疗信息状态（每天最新一条为1，其他为0）
     */
    public static function updateTreatmentStatus($patientUser)
    {
        $startTime = strtotime(date('Y-m-d', time()));
        $endTime = $startTime + 86399;
        $todayHaveTreat = Treatment::find()
            ->where([
                'status' => Treatment::STATUS_ENABLE,
                'patient_card_id' => $patientUser->patient_card_id
            ])
            ->andWhere(['between', 'created_at', $startTime, $endTime])
            ->asArray()
            ->one();
        if (!$todayHaveTreat) {
            return true;
        }
        return Treatment::updateAll(
            ['status' => Treatment::STATUS_INVALID],
            ['and', ['between', 'created_at', $startTime, $endTime], ['patient_card_id' => $patientUser->patient_card_id]]);
    }

    /**
     * 所有模板新增
     *
     * @param $params
     * @return array|int
     */
    public static function createClinicTreatment($params, $patientUser)
    {
        $model = new Treatment();
        $model->project_id = $params['project_id'];
        $model->treatment_room_id = $params['treatment_room_id'];
        $model->patient_card_id = $patientUser->patient_card_id;
        $model->clinic_project_id = $params['clinic_project_id'];
        $model->clinic_project_name = $params['clinic_project_name'];
        $model->name = $patientUser->name;
        $model->birthday = $patientUser->birthday;
        $model->age = $patientUser->age;
        $model->gender = $patientUser->gender;
        $model->mobile = $patientUser->mobile;
        $model->clinic_time = time();
        $model->clinic_num = isset($params['clinic_num']) && $params['clinic_num'] ? $params['clinic_num'] : 1; // 半舱311不传
        $userTreatmentProject = UserTreatmentProject::findOne([
            'patient_card_id' => $patientUser->patient_card_id,
            'clinic_project_id' => $params['clinic_project_id'],
            'project_id' => $params['project_id']
        ]);
        $model->total_num = isset($userTreatmentProject) && $userTreatmentProject->total_num ? ($userTreatmentProject->total_num - $userTreatmentProject->have_treat_num - $params['clinic_num']) : 0;
        $model->clinic_id = $patientUser->clinic_id;
        $clinicIs = Clinic::findOne($patientUser->clinic_id);
        $model->clinic_name = isset($clinicIs->name) ? $clinicIs->name : '';
        $model->remark = $params['remark'];
        $model->patient_signature = $params['patient_signature'];
        $model->status = Treatment::STATUS_ENABLE;
        $model->operate_id = $params['operate_id'];
        $memberAttrIs = Attr::findOne($params['operate_id']);
        $model->operate_profession = isset($memberAttrIs->profession_name) ? $memberAttrIs->profession_name : '';
        $model->operate_name = $params['operate_name'];
        if ($model->save() == false) {
           // var_dump($model->errors);exit;
            return false;
        }
        return ['new_id' => $model->id, 'patient_card_id' => $patientUser->patient_card_id];
    }

    /**
     * 模板1（308）添加详情
     *
     * @param $params
     * @param $lastTreat
     * @return bool|int
     * @throws \yii\db\Exception
     */
    public static function createTreatFirstDetail($params, $lastTreat)
    {
        $addList = [];
        if ($params['list'] && !is_array($params['list'])) {
            $params['list'] = json_decode($params['list']);
        }
        if (is_array($params['list'])) {
            foreach ($params['list'] as $k => $v) {
                $add['project_id'] = $params['project_id'];
                $add['patient_card_id'] = $lastTreat['patient_card_id'];
                $add['clinic_treatment_id'] = $lastTreat['new_id'];

                $add['body_parts_large_id'] = $v->body_parts_large_id;
                $add['body_parts_large_name'] = $v->body_parts_large_name;

                // 小部位不必填，没有小部位时小部位也是大部位
                $add['body_parts_small_id'] = $v->body_parts_small_id ? $v->body_parts_small_id : $v->body_parts_large_id;
                $add['body_parts_small_name'] = $v->body_parts_small_name ? $v->body_parts_small_name : $v->body_parts_large_name;
                $add['num'] = $v->num;
                $add['dose'] = $v->dose;

                $add['created_at'] = time();
                $add['updated_at'] = time();
                $addList[] = $add;
            }
            $haveAdd = Yii::$app->db->createCommand()
                ->batchInsert(TreatmentDetail::tableName(),
                    [
                        'project_id', 'patient_card_id', 'clinic_treatment_id', 'body_parts_large_id', 'body_parts_large_name',
                        'body_parts_small_id', 'body_parts_small_name', 'num', 'dose', 'created_at', 'updated_at'
                    ],
                    $addList)
                ->execute();
            return $haveAdd;
        }
        return true;
    }

    /**
     * 311、其他模板新增详情
     *
     * @param $params
     * @param $lastTreat
     * @return array|int
     * @return bool
     */
    public static function createTreatOtherDetail($params, $lastTreat, $patientUser)
    {
        $model = new TreatmentDetail();
        $model->project_id = $params['project_id'];
        $model->patient_card_id = $patientUser->patient_card_id;
        $model->clinic_treatment_id = $lastTreat['new_id'];
        $model->body_parts_large_id = isset($params['body_parts_large_id']) && $params['body_parts_large_id'] ? $params['body_parts_large_id'] : 0;
        $model->body_parts_large_name = isset($params['body_parts_large_name']) && $params['body_parts_large_name'] ? $params['body_parts_large_name'] : '';
        $model->body_parts_small_id = 0;
        $model->body_parts_small_name = '';
        $model->num = $params['num'];
        $model->dose = is_string($params['dose']) ? $params['dose'] : (string)$params['dose'];
        if ($model->save() == false) {
//            var_dump($model->errors);exit;
            return false;
        }
        return true;
    }

    /**
     * 治疗信息操作日志
     *
     * @param $params
     * @param $patientUser
     * @return bool
     */
    public static function createOperateLog($params, $patientUser)
    {
        $model = new OperateLog();
        $model->project_id = $params['project_id'];
        $model->patient_user_id = $patientUser->id;
        $model->action_type = OperateLog::ACTION_TYPE_PATIENT_TREATMENT;

        $userTreatmentProject = UserTreatmentProject::findOne([
            'patient_card_id' => $patientUser->patient_card_id,
            'clinic_project_id' => $params['clinic_project_id'],
            'project_id' => $params['project_id']
        ]);
        $totalNum = isset($userTreatmentProject) && $userTreatmentProject->total_num
            ? ($userTreatmentProject->total_num - $userTreatmentProject->have_treat_num - $params['clinic_num'])
            : 0;

        $model->action_content = '治疗项目：【' . $params['clinic_project_name']
            . '】 本次治疗：【' . $params['clinic_num']
            . '】 本次剩余：【' . $totalNum . '】';
        $model->operate_name = $params['operate_name'];
        $model->operate_id =$params['operate_id'];
        if ($model->save() == false) {
            return false;
        }
        return true;
    }

    /**
     * 更新患者治疗项目信息
     *
     * @param $params
     * @return bool
     */
    public static function updateUserTreatmentProject($params, $patientUser)
    {
        // 更新用户治疗项目(最后一次)
        $userTreatmentProject = UserTreatmentProject::findOne([
            'project_id' => $params['project_id'],
            'patient_card_id' => $patientUser->patient_card_id,
            'clinic_project_id' => $params['clinic_project_id']
        ]);
        if ($userTreatmentProject) {
            $res = UserTreatmentProject::updateAll(
                [
                    'have_treat_num' => $params['clinic_num'] + $userTreatmentProject->have_treat_num,
                    'clinic_total_num' => $params['clinic_num'],
                    'clinic_end_time' => time(),
                    'updated_at' => time()
                ],
                ['id' => $userTreatmentProject->id]
            );
            if (!$res) {
                return false;
            }
        }
        return true;
    }

    /**
     * 查看治疗详情
     *
     * @param $params
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getTreatDetail($params, $page, $pageSize)
    {
        $patientIs = User::findOne($params['patient_user_id']);
        $where = [
            'project_id' => $params['project_id'],
            'treatment_room_id' => $params['treatment_room_id'],
            'patient_card_id' => $patientIs->patient_card_id,
            'clinic_project_id' => $params['clinic_project_id']
        ];

        $query = Treatment::find()
            ->select('id, name, total_num, clinic_num, patient_signature, created_at')
            ->where($where)
            ->orderBy('id desc');

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $treatmentAll = $query
            ->asArray()
            ->all();

        // 治疗项目信息
        $clinicProjectIs = Project::findOne($params['clinic_project_id']);
        foreach ($treatmentAll as &$val) {

            // 根据项目的模版判断是否有治疗详情
            if ($clinicProjectIs->template == Project::TEMPLATE_308 || $clinicProjectIs->template == Project::TEMPLATE_NAJIN) {
                $val['list'] = TreatmentDetail::find()
                    ->select('id, body_parts_large_name, body_parts_small_name, num, dose')
                    ->where(['clinic_treatment_id' => $val['id']])
                    ->asArray()
                    ->all();
            } elseif($clinicProjectIs->template == Project::TEMPLATE_311) {
                $treatDetail = TreatmentDetail::find()
                    ->select('id, dose')
                    ->where(['clinic_treatment_id' => $val['id']])
                    ->asArray()
                    ->one();
                $val['dose'] = $treatDetail['dose'];
            } elseif($clinicProjectIs->template == Project::TEMPLATE_HALF_311) {
                $treatDetail = TreatmentDetail::find()
                    ->select('id, body_parts_large_name, dose')
                    ->where(['clinic_treatment_id' => $val['id']])
                    ->asArray()
                    ->one();
                $val['body_parts_large_name'] = $treatDetail['body_parts_large_name'];
                $val['dose'] = $treatDetail['dose'];
            }
            $val['created_at'] = $val['created_at'] ? date('Y-m-d H:i', $val['created_at']) : '';
        }
        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $treatmentAll,
        ];
    }

    /**
     * 判断是否有权限
     *
     * @param $memberId
     * @param $isSuper
     * @param $projectId
     * @return array|bool
     */
    public static function getMemberPermission($memberId, $isSuper, $projectId)
    {
        if ($isSuper == Member::IS_SUPER_YES) {
            return true;
        }

        // 非超管，获取角色ID
        $userRoleList = UserRole::find()->select('role_id')->where(['member_id' => $memberId, 'project_id' => $projectId])->asArray()->all();
        $userRoleIs = array_column($userRoleList, 'role_id');

        $menuAll = RolePermission::find()->alias('a')->select(['b.*'])
            ->join('INNER JOIN', Menu::tableName().' AS b', 'b.id = a.permission_id')
            ->where([
                'a.permission_type' => RolePermission::PERMISSION_TYPE_MENU,
                'a.project_id' => $projectId,
                'b.status' => Menu::STATUS_ENABLE,
            ])
            ->andWhere(['a.role_id' => $userRoleIs])->asArray()->all();

        // 按照是否有治疗室菜单ID权限 来 判断是否可以登录治疗室pad端
        $menuAllId = array_column($menuAll, 'id');
        if (in_array(Menu::MENU_TREATMENT, $menuAllId)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 部位列表
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getBodyParts()
    {
        $bodyParts = BodyParts::find()->select('id, pid, body_parts_name')->where(['pid' => 0, 'status' => BodyParts::STATUS_ENABLE])->asArray()->all();
        foreach ($bodyParts as &$val) {
            $val['child'] = BodyParts::find()->select('id, pid, body_parts_name')->where(['pid' => $val['id'], 'status' => BodyParts::STATUS_ENABLE])->asArray()->all();
        }
        return $bodyParts;
    }

    /**
     * 半舱311部位列表
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getBcBodyParts()
    {
        $bcBodyParts = BcBodyParts::find()->select('id, bc_parts_name')->where(['status' => BodyParts::STATUS_ENABLE])->asArray()->all();

        return $bcBodyParts;
    }

}